package com.example.messagemodule.utils;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.UserInfoConstants;
import com.example.messagemodule.adapter.ConversationMessageAdapter;
import com.example.messagemodule.entity.HbasePatientImManagerEntity;
import com.example.messagemodule.manager.MessageType;
import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMFileMessageBody;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMLocationMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.EMVideoMessageBody;
import com.hyphenate.chat.EMVoiceMessageBody;
import com.hyphenate.chat.adapter.message.EMAMessage;
import com.hyphenate.chat.adapter.message.EMAMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.examination.mlib.interfaceapi.MessageApi;
import com.examination.mlib.interfaceapi.MessageCallApi;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.CommonUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MessageUtils {
    /**
     * android-rn
     *
     * @param context
     * @param pluginId
     * @param componentName
     */
    public static void push(Context context, String pluginId, String componentName) {
        MessageCallApi messageCallApi = (MessageCallApi) ARouter.getInstance().build(ARouterConstants.MessageModuleImpl).navigation();
        messageCallApi.Android2RnPush(context, pluginId, componentName);
    }

    /**
     * rn-android
     *
     * @param context
     * @param pluginId
     * @param componentName
     * @param bundle
     */
    public static void push(Context context, String pluginId, String componentName, Bundle bundle) {
        MessageCallApi messageCallApi = (MessageCallApi) ARouter.getInstance().build(ARouterConstants.MessageModuleImpl).navigation();
        messageCallApi.Android2RnPush(context, pluginId, componentName, bundle);
    }

    /**
     * 环信登录
     *
     * @param imUsername
     * @param imPassword
     * @param emCallBack
     */
    public static void imLogin(String imUsername, String imPassword, EMCallBack emCallBack) {
        EMClient.getInstance().login(imUsername, imPassword, emCallBack);
    }

    /**
     *
     */
    public static String history2Json(EMCursorResult<EMMessage> emMessageEMCursorResult) {
        HashMap<String, Object> messageData = new HashMap<>();
        if (emMessageEMCursorResult != null) {
            List<EMMessage> data = emMessageEMCursorResult.getData();
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getType() == EMMessage.Type.CMD) {
                    data.remove(i);
                }
            }
            Object[] list = new Object[data.size()];
            for (int i = 0; i < data.size(); i++) {
                HashMap<String, Object> messageList = new HashMap<>();
                HashMap<String, Object> messagebody = new HashMap<>();
                EMMessage emMessage = data.get(i);
                messageList.put("username", emMessage.getUserName());
                messageList.put("timestamp", emMessage.getMsgTime());
                messageList.put("messageId", emMessage.getMsgId());
                messageList.put("ext", emMessage.ext());
                EMMessage.Type type = emMessage.getType();
                switch (type) {
                    case TXT:
                        messageList.put("msgType", 0);
                        break;
                    case IMAGE:
                        messageList.put("msgType", 1);
                        break;
                    case VIDEO:
                        messageList.put("msgType", 2);
                        break;
                    case LOCATION:
                        messageList.put("msgType", 3);
                        break;
                    case VOICE:
                        messageList.put("msgType", 4);
                        break;
                    case FILE:
                        messageList.put("msgType", 5);
                        break;
                    case CMD:
                        messageList.put("msgType", 6);
                        break;
                    case CUSTOM:
                        messageList.put("msgType", 7);
                        break;

                }
                messageList.put("chattype", emMessage.getChatType());
                messageList.put("from", emMessage.getFrom());
                messageList.put("to", emMessage.getTo());
                if (emMessage.getType() == EMMessage.Type.TXT) {
                    EMTextMessageBody body = (EMTextMessageBody) emMessage.getBody();
                    if (body != null && body.getMessage() != null) {
                        messagebody.put("text", body.getMessage());
                    }
                } else if (emMessage.getType() == EMMessage.Type.IMAGE) {
                    EMImageMessageBody body = (EMImageMessageBody) emMessage.getBody();
                    messagebody.put("filename", body.getFileName());
                    messagebody.put("height", body.getHeight());
                    messagebody.put("thumbnailsecret", body.getThumbnailSecret());
                    messagebody.put("thumbnailurl", body.getThumbnailUrl());
                    messagebody.put("width", body.getWidth());
                    messagebody.put("remotePath", body.getRemoteUrl());
                } else if (emMessage.getType() == EMMessage.Type.VOICE) {
                    EMVoiceMessageBody body = (EMVoiceMessageBody) emMessage.getBody();
                    messagebody.put("localurl", body.getLocalUrl());
                    messagebody.put("duration", body.getLength());
                    messagebody.put("remotePath", body.getRemoteUrl());
                    messagebody.put("secret", body.getSecret());
                    messagebody.put("describecontents", body.describeContents());
                } else if (emMessage.getType() == EMMessage.Type.VIDEO) {
                    EMVideoMessageBody body = (EMVideoMessageBody) emMessage.getBody();
                    messagebody.put("duration", body.getDuration());
                    messagebody.put("loaclthumb", body.getLocalThumb());
                    messagebody.put("thumbnailheight", body.getThumbnailHeight());
                    messagebody.put("thumbnailsercet", body.getThumbnailSecret());
                    messagebody.put("thumbnailurl", body.getThumbnailUrl());
                    messagebody.put("thumbnailwidth", body.getThumbnailWidth());
                    messagebody.put("videofilelength", body.getVideoFileLength());
                } else if (emMessage.getType() == EMMessage.Type.CMD) {
                    EMCmdMessageBody body = (EMCmdMessageBody) emMessage.getBody();
                    messagebody.put("params", body.getParams());
                    messagebody.put("action", body.action());

                } else if (emMessage.getType() == EMMessage.Type.FILE) {
                    EMFileMessageBody body = (EMFileMessageBody) emMessage.getBody();
                    messagebody.put("filename", body.getFileName());
                    messagebody.put("localurl", body.getLocalUrl());
                    messagebody.put("remoteurl", body.getRemoteUrl());
                    messagebody.put("secret", body.getSecret());

                } else if (emMessage.getType() == EMMessage.Type.LOCATION) {
                    EMLocationMessageBody body = (EMLocationMessageBody) emMessage.getBody();
                    messagebody.put("address", body.getAddress());
                    messagebody.put("latitude", body.getLatitude());
                    messagebody.put("longitude", body.getLongitude());

                } else if (emMessage.getType() == EMMessage.Type.CUSTOM) {
                    EMCustomMessageBody body = (EMCustomMessageBody) emMessage.getBody();
                    Map<String, String> params = body.getParams();
                    String event = body.event();
                    int describeContents = body.describeContents();
                    Set<Map.Entry<String, String>> entries = params.entrySet();
                    HashMap<String, Object> paramsMap = new HashMap<>();
                    for (Map.Entry<String, String> entrie : entries
                    ) {
                        paramsMap.put(entrie.getKey(), entrie.getValue());
                    }
                    messagebody.put("customExt", params);
                    messagebody.put("event", event);
                    messagebody.put("ext", paramsMap);
                }
                messageList.put("body", messagebody);
                list[i] = messageList;
            }
            messageData.put("list", list);
            messageData.put("cursor", emMessageEMCursorResult.getCursor());
        } else {
            messageData.put("list", null);
            messageData.put("cursor", null);
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("result", messageData);
        return CommonUtils.getModuleCommonUtils().getMaptoJson(hashMap);
    }

    /**
     * 获取环信历史消息
     *
     * @param toChatUsername
     * @param chatType
     * @param index
     * @param startMsgId
     * @return
     */

    public static List<EMMessage> getImHistoryMsg(String toChatUsername, EMConversation.EMConversationType chatType, int index, String startMsgId) {
        EMConversation.EMConversationType chat;
        List<EMMessage> data = new ArrayList<>();
        try {
            data.clear();
            if (chatType == null) {
                EMCursorResult<EMMessage> cursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(toChatUsername, EMConversation.EMConversationType.Chat, index, startMsgId);
                data.addAll(cursorResult.getData());
            } else {
                EMCursorResult<EMMessage> cursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(toChatUsername, chatType, index, startMsgId);
                data.addAll(cursorResult.getData());
            }
        } catch (HyphenateException e) {
            e.printStackTrace();
        }
        return data;
    }

    public static String getImHistoryMsgJSON(String toChatUsername, int chatType, int index, String startMsgId) {
//        EMConversation.EMConversationType chat;
        String data;
        EMCursorResult<EMMessage> cursorResult = null;
        try {
            if (chatType == 0) {
                cursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(toChatUsername, EMConversation.EMConversationType.Chat, index, startMsgId);
            } else if (chatType == 1) {
                cursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(toChatUsername, EMConversation.EMConversationType.Chat, index, startMsgId);
            } else if (chatType == 2) {
                cursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(toChatUsername, EMConversation.EMConversationType.ChatRoom, index, startMsgId);
            }
        } catch (HyphenateException e) {
            e.printStackTrace();
            ALog.i("getImHistoryMsgJSON", "getImHistoryMsgJSON: " + e.getMessage());
        }
        return history2Json(cursorResult);

    }


    private static EMMessage emmessage;
    private static EMAMessage emaMessage = new EMAMessage();

    public static EMMessage sendMessage(Context context, String datajson) throws JSONException {
//        Map datamap = (Map) JSON.parse(datajson);
        org.json.JSONObject json = new org.json.JSONObject(datajson);
        String to = (String) json.getString("to");
        int msgType = (Integer) json.getInt("msgType");
//        String ext = (String) datamap.get("ext");
        JSONObject jsonObject = new JSONObject();
        org.json.JSONObject ext = json.getJSONObject("ext");
        String s = ext.toString();
//        Map<String,Object> extMap = jsonObject.getJSONObject(ext);
//        Map<String,Object> extMap = JSON.parseObject(objectJSONObject,Map.class);
//        for (int i = 0; i < jsonArray.size(); i++) {
//            JSONObject arrayJSONObject = jsonArray.getJSONObject(i);
//
//        }
        if (msgType == EMAMessageBody.EMAMessageBodyType_TEXT) {
            //文本类型 0
            String text = (String) json.get("text");
            String content = CommonUtils.decodeUTF8(text);
            ALog.d("发送文本消息", "sendMessage: " + content);
            emmessage = EMMessage.createTxtSendMessage(content, to);

        } else if (msgType == EMAMessageBody.EMAMessageBodyType_IMAGE) {
            //图片类型 1
            String uri = (String) json.get("imgUrl");
//            CommonUtils.getModuleCommonUtils().Uri2Path(context,uri);
            //imageUri为图片本地资源标志符，false为不发送原图（默认超过100k的图片会压缩后发给对方），需要发送原图传true
            emmessage = EMMessage.createImageSendMessage(uri, false, to);
            //如果是群聊，设置chattype，默认是单聊
        } else if (msgType == EMAMessageBody.EMAMessageBodyType_VIDEO) {
            //视频类型 2

        } else if (msgType == EMAMessageBody.EMAMessageBodyType_LOCATION) {
            //位置类型 3

        } else if (msgType == EMAMessageBody.EMAMessageBodyType_VOICE) {
            //音频类型 4
            //voiceUri为语音文件本地资源标志符，length为录音时间(秒)
            emmessage = EMMessage.createVoiceSendMessage(Uri.parse((String) json.get("filePath")), (int) json.get("fileTimeLength"), to);

        } else if (msgType == EMAMessageBody.EMAMessageBodyType_FILE) {
            //文件类型 5

        } else if (msgType == EMAMessageBody.EMAMessageBodyType_COMMAND) {
            //类型 6
            emmessage = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
            ALog.i("CMD", "sendMessage: " + datajson);

        } else if (msgType == EMAMessageBody.EMAMessaeBody_Type_CUSTOM) {
            //自定义消息 7
            emmessage = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
        }
        Map<String, Object> extMap = (Map<String, Object>) JSON.parse(s);
        setExt(emmessage, extMap, false);
        return emmessage;
    }

    public static void setExt(EMMessage message, Map<String, Object> extMap, boolean isLast) throws JSONException {
        if (extMap == null) {
            return;
        }
        Set<Map.Entry<String, Object>> entries = extMap.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> next = iterator.next();
            if (next != null) {
                if (next.getValue() == null || next.getKey() == null) {
                    return;
                }
                if (next.getValue() instanceof Long) {
                    message.setAttribute((String) next.getKey(), (long) next.getValue());
                } else if (next.getValue() instanceof String) {
                    if (next.getKey().equals("templateExt")) {
                        if (isLast) {
                            org.json.JSONObject jsonObject = new org.json.JSONObject((String) next.getValue());
                            if (jsonObject.has("last")) {
                                jsonObject.remove("last");
                                jsonObject.put("last", true);
                            }
                            if (jsonObject.has("lastPic")) {
                                jsonObject.remove("lastPic");
                                jsonObject.put("lastPic", true);
                            }
                            message.setAttribute((String) next.getKey(), jsonObject);
                        } else {
                            message.setAttribute((String) next.getKey(), new org.json.JSONObject((String) next.getValue()));
                        }
                    } else {
                        message.setAttribute((String) next.getKey(), (String) next.getValue());
                    }
                } else if (next.getValue() instanceof Integer) {
                    message.setAttribute((String) next.getKey(), (int) next.getValue());
                } else if (next.getValue() instanceof BigDecimal) {
                    String s1 = String.valueOf(next.getValue());
                    message.setAttribute(next.getKey(), s1);
                } else if (next.getValue() instanceof JSONArray) {
                    message.setAttribute((String) next.getKey(), (JSONArray) next.getValue());
                } else if (next.getValue() instanceof Double) {
                    message.setAttribute((String) next.getKey(), ((Double) next.getValue()).intValue());
                } else if (next.getValue() instanceof JSONObject) {
                    String s1 = String.valueOf(next.getValue()).toString();
                    org.json.JSONObject jsonObject1 = null;
                    try {
                        jsonObject1 = new org.json.JSONObject(s1);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    message.setAttribute((String) next.getKey(), jsonObject1);
                }
            }
        }
    }


    /**
     * im消息发送
     */
    public static void sendImMsg(Context context, String datajson, MessageApi messageApi) throws JSONException {
        EMMessage emMessage = sendMessage(context, datajson);
        ALog.i("sendImMsg", "sendImMsg: " + emMessage.ext());
        ALog.i("sendImMsg", "sendImMsg: " + emMessage.toString());
        if (emMessage == null) {
            ALog.d("消息发送失败", "emMessage is null");
            messageApi.onSuccess("消息发送失败");
        }
        // 环信发送消息
        EMClient.getInstance().chatManager().sendMessage(emMessage);
        //发送消息回调
        emMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                ALog.d("消息发送成功", "onSuccess: ");
                String s = emMessageJson(emMessage, false);
                //向广播接收器传递数据
                MessageCallApi messageCallApi = (MessageCallApi) ARouter.getInstance().build(ARouterConstants.MessageModuleImpl).navigation();
                messageCallApi.Android2RnBroadcast(context, "ReceiveOrdinaryChatMessage", s);
                messageApi.onSuccess(s);
            }

            @Override
            public void onError(int i, String s) {
                messageApi.onSuccess("消息发送失败" + s);
                ALog.d("消息发送失败", "onError: " + s);
            }

            @Override
            public void onProgress(int i, String s) {
            }
        });
    }


    //回调消息判断逻辑
    public static String emMessageJson(EMMessage emmessage, boolean isRecall) {
        HashMap<String, Object> messageMap = new HashMap<>();
        HashMap<String, Object> bodymap = new HashMap<>();
        EMMessage.Type type = emmessage.getType();
        if (type == EMMessage.Type.TXT) {
            messageMap.put("msgType", 0);
            EMTextMessageBody body = (EMTextMessageBody) emmessage.getBody();
            if (body != null && body.getMessage() != null) {
                String message = body.getMessage();
                bodymap.put("text", body.getMessage());
            }
        } else if (type == EMMessage.Type.IMAGE) {
            messageMap.put("msgType", 1);
            EMImageMessageBody body = (EMImageMessageBody) emmessage.getBody();
            if (body != null) {
                int width = body.getWidth();
                String fileName = body.getFileName();
                int height = body.getHeight();
                String thumbnailUrl = body.getThumbnailUrl();
                String thumbnailSecret = body.getThumbnailSecret();
                bodymap.put("filename", body.getFileName());
                bodymap.put("height", body.getHeight());
                bodymap.put("thumbnailsecret", body.getThumbnailSecret());
                bodymap.put("thumbnailurl", body.getThumbnailUrl());
                bodymap.put("width", body.getWidth());
                bodymap.put("remotePath", body.getRemoteUrl());
            }
        } else if (type == EMMessage.Type.VOICE) {
            messageMap.put("msgType", 4);
            EMVoiceMessageBody body = (EMVoiceMessageBody) emmessage.getBody();
            if (body != null) {
                bodymap.put("localurl", body.getLocalUrl());
                bodymap.put("duration", body.getLength());
                bodymap.put("thumbnailRemotePath", body.getRemoteUrl());
                bodymap.put("secret", body.getSecret());
                bodymap.put("describecontents", body.describeContents());
                bodymap.put("remotePath", body.getRemoteUrl());
            }
            File path = new File(body.getLocalUrl());
            if (path != null && path.exists()) {
                path.delete();
            }
        } else if (type == EMMessage.Type.CUSTOM) {
            messageMap.put("msgType", 7);
            EMCustomMessageBody body = (EMCustomMessageBody) emmessage.getBody();
            HashMap<String, Object> paramsMap = new HashMap<>();
            if (body != null) {
                Set<Map.Entry<String, Object>> entries = paramsMap.entrySet();
                for (Map.Entry<String, Object> entrie : entries
                ) {
                    paramsMap.put(entrie.getKey(), entrie.getValue());
                }
                bodymap.put("customExt", body.getParams());
                bodymap.put("event", body.event());
                ALog.i("EVENT", "emMessageJson: EVENT" + body.event());
                bodymap.put("ext", paramsMap);
            }
        } else if (type == EMMessage.Type.CMD) {
            messageMap.put("msgType", 6);
            EMCmdMessageBody body = (EMCmdMessageBody) emmessage.getBody();
            if (body != null) {
                bodymap.put("action", body.action());
                bodymap.put("params", body.getParams());
            }
        }
        messageMap.put("timestamp", emmessage.getMsgTime());
        messageMap.put("from", emmessage.getFrom());
        messageMap.put("messageId", emmessage.getMsgId());
        messageMap.put("userName", emmessage.getUserName());
        messageMap.put("body", bodymap);
        messageMap.put("to", emmessage.getTo());
        messageMap.put("ext", emmessage.ext());
        ALog.d("EXT", "emMessageJson: " + emmessage.ext());
        messageMap.put("result", true);
        messageMap.put("isRecall", isRecall);
        String s = new Gson().toJson(messageMap);
        return s;
    }

    /**
     * 判断当前im是否登录
     *
     * @return
     */
    public static boolean isImLogin() {
        if (EMClient.getInstance().isLoggedInBefore()) {
            return true;
        } else {
            return false;
        }
    }

    public static void imLogin(Context context, MessageApi messageApi) {
        String imAccount = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.imAccount, null);
        String imPassword = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.imPassword, null);

        if (imAccount != null && imPassword != null) {
            EMClient.getInstance().login(imAccount, imPassword, new EMCallBack() {
                @Override
                public void onSuccess() {
                    messageApi.onSuccess("登录成功");
                }

                @Override
                public void onError(int code, String error) {
                    messageApi.onSuccess("" + error);
                }

                @Override
                public void onProgress(int progress, String status) {
                }
            });
        } else {
            ALog.e("环信登录失败");
        }
    }

    public static void sendBrocast(Context context, String key, String value) {
        MessageCallApi messageCallApi = (MessageCallApi) ARouter.getInstance().build(ARouterConstants.MessageModuleImpl).navigation();
        messageCallApi.sendBrocast(context, key, value);
    }

    public static boolean logoutIM() {
        if (EMClient.getInstance().isLoggedInBefore()) {
            EMClient.getInstance().logout(true);
            ALog.d("logoutIM", "退出成功");
        }
        return true;


    }

    public static void uploadHMSPushToken(String appId, String token) {
        // 上传 token 方法，token 是通过广播接收器接收到的
        EMClient.getInstance().sendHMSPushTokenToServer(appId, token);
    }


    public static void disposeHbaseMessage(HbasePatientImManagerEntity.DataBean hbaseMessage, String account) {
        switch (hbaseMessage.getMsgType()) {
            case MessageType.Message_TXT: {
                hbaseMessage.setType(disposeTxtMessage(hbaseMessage.getFromAccount(),account,hbaseMessage.getExt()));
            }
            break;
            case MessageType.Message_IMG: {
                hbaseMessage.setType(disposeImageMessage(hbaseMessage.getFromAccount(),account));
            }
            break;
            case MessageType.Message_AUD:{
                hbaseMessage.setType(disposeAudioMessage(hbaseMessage.getFromAccount(),account));
            }
            break;
            case MessageType.Message_CUS:{
                hbaseMessage.setType(disposeCustomeMessage(hbaseMessage.getCustomEvent(),hbaseMessage.getFromAccount(),account,hbaseMessage.getChargesListId()));
            }
            break;
            default:
                ALog.e(hbaseMessage.getMsgType() + "MessageType is no definition");
        }
    }

    public static void disposeEMMessage(HbasePatientImManagerEntity.DataBean hbaseMessage, String account){
        EMMessage emMessage = hbaseMessage.getEmMessage();
        switch (emMessage.getType()){
            case TXT:
                hbaseMessage.setType(disposeTxtMessage(emMessage.getFrom(),account,new Gson().toJson(emMessage.ext())));
                break;
            case IMAGE:
                hbaseMessage.setType(disposeImageMessage(emMessage.getFrom(),account));
                break;
            case VOICE:
                hbaseMessage.setType(disposeAudioMessage(emMessage.getFrom(),account));
                break;
            case CUSTOM:
                EMCustomMessageBody body = (EMCustomMessageBody) emMessage.getBody();
                hbaseMessage.setType(disposeCustomeMessage(body.event(),emMessage.getFrom(),account,hbaseMessage.getChargesListId()));
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + emMessage.getType());
        }
    }



    private static int disposeTxtMessage(String fromAccount, String account, String ext){
        if (TextUtils.equals(fromAccount,account)) {
            boolean first = false;
            if (!TextUtils.isEmpty(ext)) {
                try {
                    org.json.JSONObject jsonObject = new org.json.JSONObject(ext);
                    if (jsonObject.has("templateExt")) {
                        String templateExt = jsonObject.getString("templateExt");
                        org.json.JSONObject jsonObject1 = new org.json.JSONObject(templateExt);
                        if (jsonObject1.has("first")) {
                            first = jsonObject1.getBoolean("first");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            if (first) {
                return MessageType.MessageType_TXT_FIRST;
            } else {
                return MessageType.RIGHT.MessageType_TXT;
            }
        } else {
            return MessageType.LEFT.MessageType_TXT;
        }
    }

    private static int disposeImageMessage(String fromAccount, String account){
        if (TextUtils.equals(fromAccount,account)) {
            return MessageType.RIGHT.MessageType_IMAGE;
        } else {
            return MessageType.LEFT.MessageType_IMAGE;
        }
    }

    private static int disposeAudioMessage(String fromAccount, String account){
        if (TextUtils.equals(fromAccount,account)) {
           return MessageType.RIGHT.MessageType_AUDIO;
        } else {
           return MessageType.LEFT.MessageType_AUDIO;
        }
    }

    private static int disposeCustomeMessage(String customEvent,String messageFrom,String fromAccount,int chargesId) {
        if (TextUtils.equals(MessageType.MessageEvent_CHARGESLIST,customEvent)) {
            //问诊单
            return MessageType.MessageType_CUSTOME_CHARGESLIST;
        } else if (TextUtils.equals(MessageType.MessageEvent_RECEIVED,customEvent)) {
            //接诊
            return MessageType.MessageType_CUSTOME_RECEIVED;
        } else if (TextUtils.equals(MessageType.MessageEvent_DOCTOR_PRESCRIBING,customEvent)) {
            //处方单
            return MessageType.MessageType_CUSTOME_DOCTOR_PRESCRIBING;
        } else if (TextUtils.equals(MessageType.MessageEvent_FINISH,customEvent)) {
            //结束
            return MessageType.MessageType_CUSTOME_FINISH;
        } else if (TextUtils.equals(MessageType.MessageEvent_TO_EVALUAT,customEvent)) {
            //评价
            return MessageType.MessageType_CUSTOME_TO_EVALUATE;
        } else if (TextUtils.equals(MessageType.MessageEvent_STOP_SEND_TEMPLATE,customEvent)) {
            //问诊结束
            return MessageType.MessageType_CUSTOME_STOP_SEND_TEMPLATE;
        } else if (TextUtils.equals(MessageType.MessageEvent_LAST_CHARGES_TEMPLATE,customEvent)) {
            //问诊模板结束
            return MessageType.MessageType_CUSTOME_LAST_CHARGES_TEMPLATE;
        } else if (TextUtils.equals(MessageType.MessageEvent_PATIENT_EVALUATE_FINISH,customEvent)) {
            //评价结果
            ConversationMessageAdapter.chargesIds.add(chargesId);
            return MessageType.MessageType_CUSTOME_PATIENT_EVALUATE_FINISH;
        } else if (TextUtils.equals(MessageType.MessageEvent_DOCTOR_EVALUATE_THANKS,customEvent)) {
            //评价结果
            ConversationMessageAdapter.chargesIds.add(chargesId);
            return MessageType.MessageType_CUSTOME_DOCTOR_EVALUATE_THANKS;
        } else if (TextUtils.equals(MessageType.MessageEvent_SETTING_PHONE_TIME,customEvent)) {
            //医生端医生设置接诊时间
            return MessageType.MessageType_CUSTOME_SETTING_PHONE_TIME;
        } else if (TextUtils.equals(MessageType.MessageEvent_SF_FINISH,customEvent)) {
            //随访结束
            return MessageType.MessageType_CUSTOME_SF_FINISH;
        } else if (TextUtils.equals(MessageType.MessageEvent_SF_SUBMIT,customEvent)) {
            //随访开始
            return MessageType.MessageType_CUSTOME_SF_SUBMIT;
        } else if (TextUtils.equals(MessageType.MessageEvent_CANCEL_APPOINTMENT_CALL,customEvent)) {
            //取消预约
            return MessageType.MessageType_CUSTOME_CANCEL_APPOINTMENT_CALL;
        } else if (TextUtils.equals(MessageType.MessageEvent_UPDATE_PHONE_TIME,customEvent)) {
            //修改电话
            return MessageType.MessageType_CUSTOME_UPDATE_PHONE_TIME;
        } else if (TextUtils.equals(MessageType.MessageEvent_MISS_PHONE_CALL,customEvent)) {
            //取消
            return MessageType.MessageType_CUSTOME_MISS_PHONE_CALL;
        } else if (TextUtils.equals(MessageType.MessageEvent_PHONE_CALL_END,customEvent)) {
//                            电话问诊结束
            return MessageType.MessageType_CUSTOME_PHONE_CALL_END;
        } else if (TextUtils.equals(MessageType.MessageEvent_REFUND,customEvent)) {
//                            退诊
            return MessageType.MessageType_CUSTOME_REFUND;
        } else if (TextUtils.equals(MessageType.MessageEvent_DELAY_CHARGE,customEvent)) {
            //延时问诊
            return MessageType.MessageType_CUSTOME_DELAY_CHARGES;
        } else if (TextUtils.equals(MessageType.MessageEvent_START_VIDEO,customEvent)) {
            //延时问诊
            return MessageType.MessageType_CUSTOME_START_VIDEO;
        } else if (TextUtils.equals(MessageType.MessageEvent_DOCTOR_REJECT_VIDEO,customEvent)) {
            //延时问诊
            return MessageType.MessageType_CUSTOME_DOCTOR_REJECT_VIDEO;
        } else if (TextUtils.equals(MessageType.MessageEvent_PATIENT_MISSED_VIDEO,customEvent)) {
            //延时问诊
            return MessageType.MessageType_CUSTOME_PATIENT_MISSED_VIDEO;
        } else if (TextUtils.equals(MessageType.MessageEvent_PATIENT_REJECT_VIDEO,customEvent)) {
            //延时问诊
            return MessageType.MessageType_CUSTOME_PATIENT_REJECT_VIDEO;
        } else if (TextUtils.equals(MessageType.MessageEvent_VIDEO_HANG_UP,customEvent)) {
            //延时问诊
            if (TextUtils.equals(messageFrom,fromAccount)) {
                return MessageType.MessageType_CUSTOME_VIDEO_HANG_UP_DOCTOR;
            } else {
                return MessageType.MessageType_CUSTOME_VIDEO_HANG_UP_PATIENT;
            }
        } else if (TextUtils.equals(MessageType.MessageEvent_ETP_CONSULTING_DRUGS,customEvent)) {
            return MessageType.MessageType_CUSTOME_ETP_CONSULTING_DRUGS;
        } else if (TextUtils.equals(MessageType.MessageEvent_PATIENT_FINISH_ASK,customEvent)) {
            return MessageType.MessageType_CUSTOME_PATIENT_FINISH_ASK;
        } else if (TextUtils.equals(MessageType.MessageEvent_CANCEL_CHARGES,customEvent)) {
            return MessageType.MessageType_CUSTOME_CANCEL_CHARGES;
        } else if (TextUtils.equals(MessageType.MessageEvent_PATIENT_END_CHARGES,customEvent)) {
            return MessageType.MessageType_CUSTOME_PATIENT_END_CHARGES;
        }else{
            return 0;
        }
    }

}
